package qualomelhor.gwt.modules.client;

import java.util.ArrayList;
import qualomelhor.database.Comparacao;
import qualomelhor.database.ParametrosSistema;
import qualomelhor.database.Produto;
import qualomelhor.database.Usuario;
import qualomelhor.gwt.modules.client.event.ImagemDisponivelEvent;
import qualomelhor.gwt.modules.client.event.ImagemNaoDisponivelEvent;
import qualomelhor.gwt.modules.client.event.ImagensJaSelecionadasEvent;
import qualomelhor.gwt.modules.client.interfaces.BuscaImagemEventHandler;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.search.client.*;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class CriarComparacao3Coisas implements EntryPoint {

	private RootPanel rootSelProdMulti;
	private RootPanel rootProdMulti;
	private RootPanel rootProdRot;
	private RootPanel rootPergunta;
	private BuscaImagemWidget biProdMulti;
	private ImageSliderWidget iswMulti;
	private VerticalPanel vertPanelProdMulti;
	private VerticalPanel vertPanelAtualProdMulti;
	private VerticalPanel vertPanelPergunta;
	final VerticalPanel tmpVertPanelProd_Show = new VerticalPanel();
	//private FlexTable tbProdutoRotacao;
	private HorizontalPanel horPanelSection;
	private TextBox txtBuscaProdMulti;
	private VerticalPanel vertPImages;
	private HorizontalPanel horPanelImg;
	private CheckBox[] listCkImg;
	private HorizontalPanel horPProsseguir;
	private ListBox listPerguntas;
	private TextBox txtPerguntaIntermed;
	private Label lbProduto;
	private Label lbPerguntaFinal;
	private HandlerRegistration lbHldRegisProd1;
	private HandlerRegistration lbHldRegisProd1_blur;
	private Button btnNext;
	private HTMLPanel htmlP = new HTMLPanel("<video style=\"width: 100%; height: 250px; border: thin solid black;\" autoplay></video>");
	private HTMLPanel htmlPCanvas = new HTMLPanel("<canvas class=\"canvasVideo\" style=\"display:none;\"></canvas>");
	private final HTMLPanel htmlImg = new HTMLPanel("<img class=\"imgFoto\" style=\"width: 100%; height: 300px;\" />");
	private HTMLPanel htmlFile;
	private HTMLPanel htmlInputFile = new HTMLPanel("<input type=\"file\" id=\"files\" name=\"files\" />");
	private FileUpload upload;
	private ISessionSuportServiceAsync serviceSupportSvc = GWT.create(ISessionSuportService.class);
	private LanguageConstants constants = GWT.create(LanguageConstants.class);
	private LanguageMessages messages = GWT.create(LanguageMessages.class);
	private Usuario u;
	private ArrayList<Produto> listProdutos = new ArrayList<Produto>(0);
	private ArrayList<String> listImageDataUrlProd = new ArrayList<String>(0);
	private int guiaAtualProd;

	int currentRow;
	FlexTable resultsTable;

	private static native boolean startScroll () /*-{ 
		$wnd.startScroll();
	}-*/;

	private static native boolean addSection () /*-{ 
		$wnd.addSection();
	}-*/;

	private static native boolean setNumProds (int numP) /*-{ 
		$wnd.numProds = numP;
		$wnd.moveToLast();
	}-*/;

	private static native boolean gameCarregado () /*-{ 
		if ($wnd.verificaGameCarregado_j) {
			return $wnd.verificaGameCarregado_j();
		} else {
			return false;
		}
	}-*/;

	public static native void setMsgTextGWT(String txt, boolean hideOnTime) /*-{
		//alert($wnd.sendMsgText2_j);
		if ($wnd.sendMsgText2_j) {
			//alert("dentro do if...");
			$wnd.sendMsgText2_j(txt, hideOnTime);
			//alert("executou o sendmsgtext2...");
		}
	}-*/;

	public static native void carregaSequenciaExpressaoGWT(String nome) /*-{
		//$wnd.alert("vai chamar o carregamento da sequencia expressao...");
		if ($wnd.carregaSequenciaExpressao_j) {
			$wnd.carregaSequenciaExpressao_j(nome);
		}
	}-*/;

	public static native void iniciaComportamentoAleatorio() /*-{
		$wnd.iniciaComportamentoAleatorio_j();
	}-*/;

	public static native void resize() /*-{
		$wnd.resizeCompMulti();
	}-*/;

	public static native String foto() /*-{
		return $wnd.snapshot();
	}-*/;

	public static native boolean hasGetUserMedia() /*-{
		if (!$wnd.hasGetUserMedia) {
			$wnd.hasGetUserMedia = function() {
				// Note: Opera is unprefixed.
				return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
	 			            navigator.mozGetUserMedia || navigator.msGetUserMedia);
	 		}
		}
		return $wnd.hasGetUserMedia();
	 	//$wnd.alert("hasGetUserMedia ok");
	}-*/;

	public static native boolean hasFileReader() /*-{
		var result = false;
		if ($wnd.File && $wnd.FileReader && $wnd.FileList && $wnd.Blob) {
	  		// Great success! All the File APIs are supported.
	  		result = true;
		} else {
		  	//$wnd.alert('The File APIs are not fully supported in this browser.');
		}

		return result;
	}-*/;	

	public static native void loadCam(String strTextoBoneco) /*-{

		//$wnd.alert("inicio loadcam");
		$wnd.localMediaStream = null;
		$wnd.ctx = null;
	 	$wnd.video = $doc.querySelector('video');
	 	$wnd.canvas = $doc.querySelector(".canvasVideo");
		//$wnd.alert("video = " + video);
	
	 	//video.addEventListener('click', snapshot, false);
		//$wnd.alert("video click ok");
	
		//$wnd.alert("$doc.getElementById = " + $doc.getElementById);
		//canvas = $doc.querySelector('canvas');
			
		//$wnd.alert("canvas = " + $wnd.canvas);
		//$wnd.alert("canvas.getContext = " + $wnd.canvas.getContext);
		$wnd.ctx = $wnd.canvas.getContext('2d');
		//$wnd.alert("ctx = " + $wnd.ctx);
	
		var onFailSoHard = function(e) {
			console.log('Reeeejected!', e);
		};
	
		//$wnd.alert("onFailSoHard ok");
	
		//$wnd.alert("snapshot ok");
	
	 	 if ($wnd.hasGetUserMedia()) {
	 		// Good to go!
	 		//$wnd.alert("getUserMedia ok");
	 	} else {
	 		$wnd.alert('getUserMedia() is not supported in your browser');
	 	}
	
		$wnd.URL = $wnd.URL || $wnd.webkitURL;
	 	//$wnd.alert("wnd.URL = " + $wnd.URL);
		navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
	 	//$wnd.alert("navigator.getUserMedia = " + navigator.getUserMedia);			
	
		if (navigator.getUserMedia) {
			//$wnd.alert("1");
			navigator.getUserMedia({video: true}, function(stream) {
				//$wnd.alert("2");
				$wnd.video.src = $wnd.URL.createObjectURL(stream);
				$wnd.localMediaStream = stream;
				$wnd.carregaSequenciaExpressao_j("Clica-Tira-Foto", false);
				$wnd.sendMsgText2_j(strTextoBoneco, false);
	
				//$wnd.alert("3");
			}, onFailSoHard);
			//$wnd.alert("4");
		} else {
			video.src = 'somevideo.webm'; // fallback.
		}
	
		if (!$wnd.snapshot) {
			$wnd.snapshot = function() {
				//$wnd.alert("snapshot");
				if ($wnd.localMediaStream) {
					var cw = $wnd.canvas.width;
		    		var ch = $wnd.canvas.height;
					//$wnd.alert("cw = " + cw + ", ch = " + ch);
					$wnd.ctx.drawImage($wnd.video, 0, 0, cw, ch);
					//$wnd.alert("draw ok");
					// "image/webp" works in Chrome 18. In other browsers, this will fall back to image/png.
					var strDataUrl = $wnd.canvas.toDataURL("image/png");
					//$wnd.alert("canvas.toDataUrl = " + strDataUrl);
					$doc.querySelector('.imgFoto').src = strDataUrl;
					//$wnd.alert("img ok");
					//var imgData = ctx.getImageData(0, 0, cw, ch);
					return strDataUrl;
				} else {
					return null;
				}
			}
		}
	}-*/;

	public static native void unLoadCam() /*-{
		if ($wnd.localMediaStream) {
			//$wnd.alert("unLoadCam inicio");
			$wnd.localMediaStream.stop();
			$wnd.localMediaStream = null;
			//$wnd.alert("unLoadCam fim");
		}
	}-*/;

	public static native void exportaAdicionaFotoFile(CriarComparacao2Coisas compInstance) /*-{
		$wnd.adicionaFotoFile_j = function(prodNum, dataUrl) {
			compInstance.@qualomelhor.gwt.modules.client.CriarComparacao2Coisas::addStreamFotoComparacao(ILjava/lang/String;)(prodNum, dataUrl);
		}
	}-*/;

	public static native void exportaAdicionaFotoURL(CriarComparacao2Coisas compInstance) /*-{
		$wnd.adicionaFotoURL_j = function(prodNum, url) {
			compInstance.@qualomelhor.gwt.modules.client.CriarComparacao2Coisas::addURLFotoComparacao(ILjava/lang/String;)(prodNum, url);
		}
	}-*/;

	public static native void loadDropFileHandler(String msgNaoEhImagem) /*-{
		$wnd.handleFileSelect = function(evt) {
			//$wnd.alert("$wnd.handleFileSelect chamado");
			evt.stopPropagation();
			evt.preventDefault();

			var url = "";

		    var files;
		    if (evt.dataTransfer) {
		    	//$wnd.alert("dataTransfer");
		    	//$wnd.alert("evt.dataTransfer.types = " + evt.dataTransfer.types);
		    	
		    	if (evt.dataTransfer.types) {
		    		//$wnd.alert("evt.dataTransfer.types.len = " + evt.dataTransfer.types.length);
					//for (var i = 0; i < evt.dataTransfer.types.length; i++) {
					//	$wnd.alert("evt.dataTransfer.types[" + i + "] = " + evt.dataTransfer.types[i]);
					//}
					url = evt.dataTransfer.getData("url") || evt.dataTransfer.getData("text/uri-list");
					//$wnd.alert("url = " + url);
		    	}

		    	files = evt.dataTransfer.files; // FileList object.
		    } else {
		    	//$wnd.alert("target.files");
		    	files = evt.target.files;
		    }

		    // files is a FileList of File objects. List some properties.
		    var output = [];
		    // Loop through the FileList and render image files as thumbnails.
		    //$wnd.alert("files.length = " + files.length);
		    if (files.length > 0) {
			    for (var i = 0; i < files.length; i++) {
			    	//$wnd.alert("i = " + i);
					f = files[i];
					//$wnd.alert("file = " + f);
					// Only process image files.
					if (!f.type.match('image.*')) {
						//$wnd.alert("nao eh uma imagem . arquivo invalido...");
						$wnd.sendMsgText2_j(msgNaoEhImagem, true);
						continue;
					} else { 
						//$wnd.alert("eh uma imagem...");
					}

					//$wnd.alert("abrindo filereader...");
					var reader = new FileReader();
					//$wnd.alert("filereader ok...");
					// Closure to capture the file information.


					reader.onload = (function(theFile) {
						return function(e) {
							// Render thumbnail.
							//$wnd.alert("prodNum = " + $wnd.prodNum + ", dataUrl = [" + e.target.result + "]");
							$wnd.adicionaFotoFile_j($wnd.prodNum, e.target.result);
						};
					})(f);

	      			// Read in the image file as a data URL.
	      			//$wnd.alert("vai ler...");
	      			reader.readAsDataURL(f);
	      			//$wnd.alert("leu...");
	    		}
		    } else {
		    	//$wnd.alert("adicionando url...:" + url + " , prod:" + $wnd.prodNum);
		    	if (url != "") {
		    		$wnd.adicionaFotoURL_j($wnd.prodNum, url);
		    	}
		    }
		}

		$wnd.handleDragOver = function(evt) {
			evt.stopPropagation();
		    evt.preventDefault();
		    evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
		}
	}-*/;

	public static native void startFileHandler(int prodNum) /*-{
		// Setup the dnd listeners.
		$wnd.prodNum = prodNum;
		var dropZone = $doc.getElementById("drop_zone");
		if (!$wnd.eventosAdicionados) {
			//$wnd.alert("dropZone = " + dropZone);
			dropZone.addEventListener("dragover", $wnd.handleDragOver, false);
			dropZone.addEventListener("drop", $wnd.handleFileSelect, false);
		}
		var fileSelect = $doc.getElementById("files");
		if (!$wnd.eventosAdicionados) {
			//$wnd.alert("fileSelect = " + fileSelect);
			fileSelect.addEventListener("change", $wnd.handleFileSelect, false);
		}
		$wnd.eventosAdicionados = true;
		//$wnd.alert("loadDropFileHandler fim");
	}-*/;

	@Override
	public void onModuleLoad() {
		System.out.println("Iniciando modulo 3 coisas...");
		htmlFile = new HTMLPanel("<div id=\"drop_zone\" class=\"fontTextAlignCenter break-word\" style=\"width: 100%; height: 200px; display: table-cell; vertical-align: middle; background-color: white; border: thin dashed red;\">" + constants.arraste_a_imagem_neste_espaco_ou_selecione_o_arquivo_no_botao_abaixo()  + "</div>");
		rootSelProdMulti = RootPanel.get("divSelProdMulti");
		rootProdMulti = RootPanel.get("divProdutoMulti");
		rootProdRot = RootPanel.get("divprodrot");
		rootPergunta = RootPanel.get("divPergunta");
		resize();
		carregaFormComparacaoMulti();
	}

	private void carregaFormQualAPergunta() {
		rootPergunta.clear();
		rootPergunta.add(new Label("Forme a pergunta:"));
		HorizontalPanel horP = new HorizontalPanel();
		rootPergunta.add(horP);
		listPerguntas = new ListBox();
		listPerguntas.addItem("Qual o melhor", "0");
		listPerguntas.addItem("Qual a melhor", "1");
		listPerguntas.addItem("O que é melhor", "2");
		listPerguntas.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent event) {
				//lbPerguntaFinal.setText(listPerguntas.getItemText(listPerguntas.getSelectedIndex()) + " " + txtPerguntaIntermed.getText().trim() + " " + txtBusca.getText().trim());
			}
		});
		horP.add(listPerguntas);

		txtPerguntaIntermed = new TextBox();
		txtPerguntaIntermed.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent event) {
				//lbPerguntaFinal.setText(listPerguntas.getItemText(listPerguntas.getSelectedIndex()) + " " + txtPerguntaIntermed.getText().trim() + " " + txtBusca.getText().trim());
			}
		});
		horP.add(txtPerguntaIntermed);

		txtBuscaProdMulti.setEnabled(false);
		horP.add(txtBuscaProdMulti);

		lbPerguntaFinal = new Label(listPerguntas.getItemText(0) + " " + txtPerguntaIntermed.getText().trim() + " " + txtBuscaProdMulti.getText().trim());
		rootProdMulti.add(lbPerguntaFinal);

		Button btnGravar = new Button("Gravar&gt;&gt;");
		rootProdMulti.add(btnGravar);
		btnGravar.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {

				ArrayList<String> listEnderecoFoto = new ArrayList<String>(0);
				for (int i = 0; i < listCkImg.length; i++) {
					if (listCkImg[i].getValue()) {
						listEnderecoFoto.add(listCkImg[i].getTitle());
					}
				}

				if (!upload.getFilename().trim().equals("")) {
					listEnderecoFoto.add(upload.getFilename().trim());
				}
			}
		});
	}

	private void carregaFormComparacaoMulti() {
		rootProdMulti.clear();
		rootProdRot.clear();
		rootPergunta.clear();

		vertPanelPergunta = new VerticalPanel();
		rootPergunta.add(vertPanelPergunta);
		vertPanelPergunta.setWidth("100%");

		vertPanelProdMulti = new VerticalPanel();
		vertPanelProdMulti.setStylePrimaryName("sizeCemPorcento");
		rootProdMulti.add(vertPanelProdMulti);
		//tbProdutoRotacao = new FlexTable();

		//horPanel.add(tbProdutoRotacao);
		//tbProdutoRotacao.getElement().setId("tbSections");
		//tbProdutoRotacao.getElement().setClassName("divCenter");
		
		//scrollRotacao.add(tbProdutoRotacao);
		//scrollRotacao.getElement().setClassName("divCenter");
		//rootProdRot.add(scrollRotacao);

		
		/*
		if (gameCarregado()) {
			//Window.alert("vai iniciar o produto e o comportamento...");
			iniciaComportamentoAleatorio();
			solicitaProduto();
		} else {
			Timer t = new Timer() {
				@Override
				public void run() {
					if (gameCarregado()) {
						this.cancel();
						iniciaComportamentoAleatorio();
						solicitaProduto();
					}
				}
			};
			t.scheduleRepeating(1000);
		}
		*/
		solicitaProduto();
	}

	private void solicitaProduto() {

		rootProdMulti.addStyleName("boxRoundedSelected");
		//Window.alert("solicitando produto1...1");
		//Window.alert("vai carregar a expressao");
		//Window.alert("solicitando produto1...2");

		iswMulti = new ImageSliderWidget(new Image[0], ImageSliderWidget.TipoAnimacao.FADE);

		final VerticalPanel tmpVertPanelProd_Web = new VerticalPanel();
		vertPanelProdMulti.add(tmpVertPanelProd_Web);
		vertPanelAtualProdMulti = tmpVertPanelProd_Web;
		tmpVertPanelProd_Web.setStylePrimaryName("divCenter");
		tmpVertPanelProd_Web.setHeight("100%");

		final VerticalPanel tmpVertPanelProd_Cam = new VerticalPanel();
		tmpVertPanelProd_Cam.setStylePrimaryName("divCenter");
		tmpVertPanelProd_Cam.setHeight("100%");

		final VerticalPanel tmpVertPanelProd_File = new VerticalPanel();
		tmpVertPanelProd_File.setStylePrimaryName("divCenter");
		tmpVertPanelProd_File.setHeight("100%");

		HorizontalPanel horPSel = new HorizontalPanel();
		rootSelProdMulti.add(horPSel);
		horPSel.setSpacing(10);

		final Label lbWeb = new Label(constants.web());
		final Button btnWeb = new Button("");
		final Label lbCam = new Label(constants.camera());
		final Button btnCam = new Button("");
		final Label lbFile = new Label(constants.upload());
		final Button btnFile = new Button("");

		if (hasGetUserMedia() && hasFileReader()) {

			VerticalPanel vertPCam = new VerticalPanel();
			horPSel.add(vertPCam);

			vertPCam.add(lbCam);
			vertPCam.setCellHorizontalAlignment(lbCam, HasHorizontalAlignment.ALIGN_CENTER);
			lbCam.setStylePrimaryName("smallfont");
			lbCam.addStyleName("fontTextAlignCenter");

			vertPCam.add(btnCam);
			btnCam.setStylePrimaryName("btnCam");

			btnCam.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {

					if (vertPanelAtualProdMulti != null && vertPanelAtualProdMulti != tmpVertPanelProd_Cam) {
						btnCam.addStyleName("boxShadow");
						lbCam.addStyleName("btnLinkSelecionado");
						btnWeb.removeStyleName("boxShadow");
						lbWeb.removeStyleName("btnLinkSelecionado");
						btnFile.removeStyleName("boxShadow");
						lbFile.removeStyleName("btnLinkSelecionado");
	
						ClientUtils.trocaWidgetWithFunction(vertPanelAtualProdMulti, new Callable() {
							@Override
							public void call() {
								//Window.alert("call chamado");
								guiaCamProd(tmpVertPanelProd_Cam);
							}
						}, tmpVertPanelProd_Cam, "", 0, 0, false, false, 0, 50, true, 2);
					}
				}
			});
		}

		VerticalPanel vertPWeb = new VerticalPanel();
		horPSel.add(vertPWeb);

		vertPWeb.add(lbWeb);
		vertPWeb.setCellHorizontalAlignment(lbWeb, HasHorizontalAlignment.ALIGN_CENTER);
		lbWeb.setStylePrimaryName("smallfont");
		lbWeb.addStyleName("fontTextAlignCenter");

		vertPWeb.add(btnWeb);
		btnWeb.setStylePrimaryName("btnWeb");

		btnWeb.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (vertPanelAtualProdMulti != null && vertPanelAtualProdMulti != tmpVertPanelProd_Web) {

					btnWeb.addStyleName("boxShadow");
					lbWeb.addStyleName("btnLinkSelecionado");
					btnCam.removeStyleName("boxShadow");
					lbCam.removeStyleName("btnLinkSelecionado");
					btnFile.removeStyleName("boxShadow");
					lbFile.removeStyleName("btnLinkSelecionado");

					ClientUtils.trocaWidgetWithFunction(vertPanelAtualProdMulti, new Callable () {
						@Override
						public void call() {
							//Window.alert("call chamado");
							guiaWebProd(tmpVertPanelProd_Web);
							//unLoadCam();
						}
						
					}, tmpVertPanelProd_Web, "", 0, 0, false, false, 0, 50, true, 2);
				}
			}
		});

		if (hasFileReader()) {

			VerticalPanel vertPFile = new VerticalPanel();
			horPSel.add(vertPFile);

			vertPFile.add(lbFile);
			vertPFile.setCellHorizontalAlignment(lbFile, HasHorizontalAlignment.ALIGN_CENTER);
			lbFile.setStylePrimaryName("smallfont");
			lbFile.addStyleName("fontTextAlignCenter");

			vertPFile.add(btnFile);
			btnFile.setStylePrimaryName("btnFile");
			btnFile.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					if (vertPanelAtualProdMulti != null && vertPanelAtualProdMulti != tmpVertPanelProd_File) {

						btnFile.addStyleName("boxShadow");
						lbFile.addStyleName("btnLinkSelecionado");
						btnCam.removeStyleName("boxShadow");
						lbCam.removeStyleName("btnLinkSelecionado");
						btnWeb.removeStyleName("boxShadow");
						lbWeb.removeStyleName("btnLinkSelecionado");

						ClientUtils.trocaWidgetWithFunction(vertPanelAtualProdMulti, new Callable () {
							@Override
							public void call() {
								//Window.alert("call chamado");
								guiaFileProd(tmpVertPanelProd_File);
							}
							
						}, tmpVertPanelProd_File, "", 0, 0, false, false, 0, 50, true, 2);
					}
				}
			});
		}

		/*************************************************************************/
		//Guia WEB aberto por padrao
		guiaWebProd(tmpVertPanelProd_Web);
		btnWeb.addStyleName("boxShadow");
		lbWeb.addStyleName("btnLinkSelecionado");
		//Fim Guia Web
		//****************************************************************************

		loadDropFileHandler(constants.este_arquivo_nao_e_uma_imagem_tente_novamente());

		
		
		/*
		vertPanelProdMulti.clear();

		//Window.alert("solicitando produto1...1");
		setMsgTextGWT(constants.digite_o_primeiro_item_que_voce_quer_comparar(), false);
		//Window.alert("vai carregar a expressao");
		carregaSequenciaExpressaoGWT("Aponta-ProdMulti");
		//Window.alert("solicitando produto1...2");
		txtBuscaProdMulti = new TextBox();
		txtBuscaProdMulti.setStylePrimaryName("textBoxPerguntaEdicao");
		vertPanelProdMulti.add(txtBuscaProdMulti);

		final Button btnBuscaProd1 = new Button(constants.proximo());
		vertPanelProdMulti.add(btnBuscaProd1);
		btnBuscaProd1.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				biProdMulti.setBusca(txtBuscaProdMulti.getText());
			}
		});

		biProdMulti = new BuscaImagemWidget();
		vertPanelProdMulti.add(biProdMulti);

		final Button btnConfirmaImagens = new Button(constants.proximo());
		btnConfirmaImagens.setEnabled(false);
		btnConfirmaImagens.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				ArrayList<String> listImagens = biProdMulti.getSelectedImagesSource();

				Image[] matrImage = new Image[listImagens.size()];
				for (int i = 0; i < listImagens.size(); i++) {
					matrImage[i] = new Image(listImagens.get(i));
				}

				listProdutos.add(new Produto(txtBuscaProdMulti.getText().trim(), "", 0L, listImagens, new ArrayList<Blob>(0),  "", new Date()));

				RootPanel rootDivTest = RootPanel.get("divtest" + (listProdutos.size() - 1));
				rootDivTest.clear();
				VerticalPanel vertPanelProdRot = new VerticalPanel();
				rootDivTest.add(vertPanelProdRot);
				//vertPanelProdRot.setHeight("300px");
				vertPanelProdRot.setStylePrimaryName("sizeCemPorcento");
				//vertPanelProdRot.addStyleName("divCenter");
				vertPanelProdRot.setBorderWidth(1);

				iswMulti = new ImageSliderWidget(matrImage, ImageSliderWidget.TipoAnimacao.SLIDE);
				iswMulti.setStylePrimaryName("divCenter");
				iswMulti.setSize("230px", "230px");
				vertPanelProdRot.add(iswMulti);
				vertPanelProdRot.setCellHorizontalAlignment(iswMulti, HasHorizontalAlignment.ALIGN_CENTER);

				Label lb = new Label(txtBuscaProdMulti.getText().trim());
				lb.setStylePrimaryName("divCenter");
				lb.addStyleName("fontTexto1");
				lb.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
				vertPanelProdRot.add(lb);
				vertPanelProdRot.setCellHorizontalAlignment(lb, HasHorizontalAlignment.ALIGN_CENTER);

				iswMulti.iniciaAnimacao();

				setNumProds(listProdutos.size());
				maisProdutoOuContinua();
			}
		});

		vertPanelProdMulti.add(btnConfirmaImagens);
		//vertPanelProd1.setCellVerticalAlignment(btnConfirmaImagens, HasVerticalAlignment.ALIGN_BOTTOM);

		biProdMulti.addImagemSelecionadaHandler(new BuscaImagemEventHandler() {
			@Override
			public void onListaPronta(ImagemDisponivelEvent event) {
				btnConfirmaImagens.setEnabled(true);
			}

			@Override
			public void onListaNaoPronta(ImagemNaoDisponivelEvent event) {
				btnConfirmaImagens.setEnabled(false);
			}

			@Override
			public void onImagensJaSelecionadas(ImagensJaSelecionadasEvent event) {
				// TODO Auto-generated method stub
				
			}
		});
		
		*/
	}

	private void showProd() {
		//Window.alert("mostrando prod 1");
		tmpVertPanelProd_Show.clear();
		vertPanelAtualProdMulti = tmpVertPanelProd_Show;
		tmpVertPanelProd_Show.setSize("100%", "100%");

		iswMulti.setStylePrimaryName("divCenter");
		iswMulti.setSize("200px", "200px");
		tmpVertPanelProd_Show.add(iswMulti);
		tmpVertPanelProd_Show.setCellHorizontalAlignment(iswMulti, HasHorizontalAlignment.ALIGN_CENTER);

		//Window.alert("mostrando prod 1.1");
		lbProduto = new Label(txtBuscaProdMulti.getText().trim());
		lbProduto.setStylePrimaryName("divCenter");
		lbProduto.addStyleName("fontTexto1");
		lbProduto.addStyleName("fontTextAlignCenter");
		lbProduto.setWidth("100%");
		lbProduto.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

		//Window.alert("mostrando prod 1.2");
		HorizontalPanel horPTmp = new HorizontalPanel();
		tmpVertPanelProd_Show.add(horPTmp);
		horPTmp.setWidth("100%");
		horPTmp.setStylePrimaryName("fontTextAlignCenter");
		horPTmp.addStyleName("divCenter");
		tmpVertPanelProd_Show.setCellHorizontalAlignment(horPTmp, HasHorizontalAlignment.ALIGN_CENTER);

		//Window.alert("mostrando prod 1.3");
		if (txtBuscaProdMulti.getText().equals("")) {
			horPTmp.add(txtBuscaProdMulti);
			
		} else {
			horPTmp.add(lbProduto);
		}

		//Window.alert("mostrando prod 1.4");
		txtBuscaProdMulti.setWidth("100%");
		aplicaEventoLabelProd("", 0, 0);

		iswMulti.iniciaAnimacao();
		rootProdMulti.setHeight("350px");

		//Window.alert("mostrando prod 1.5");
		btnNext = new Button(constants.proximo_item());
		tmpVertPanelProd_Show.add(btnNext);
		btnNext.setWidth("100%");
		tmpVertPanelProd_Show.setCellHorizontalAlignment(btnNext, HasHorizontalAlignment.ALIGN_CENTER);
		btnNext.setStylePrimaryName("btnNext");
		btnNext.getElement().getStyle().setFontSize(20, Unit.PX);

		btnNext.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				//Window.alert("disparado click event...");
				//Window.alert("txtBuscaProd1.getText() = " + txtBuscaProd1.getText());
				if (!txtBuscaProdMulti.getText().trim().equals("")) {
					removeEventoLabelProd1();
					rootProdMulti.setHeight("300px");
					btnNext.getElement().getStyle().setVisibility(Visibility.HIDDEN);
					maisProdutoOuContinua();
					rootSelProdMulti.getElement().getStyle().setVisibility(Visibility.HIDDEN);
				} else {
					carregaSequenciaExpressaoGWT("Opps");
					setMsgTextGWT(constants.oppss_por_favor_preencha_o_nome_deste_item(), false);
					txtBuscaProdMulti.setFocus(true);
				}
				//Window.alert("fim do click event...");
			}
		});
		//Window.alert("mostrando prod 1.6");
	}

	private void guiaWebProd(final VerticalPanel tmpVertPanelProd_Web) {
		vertPanelAtualProdMulti = tmpVertPanelProd_Web;
		guiaAtualProd = 1;

		carregaSequenciaExpressaoGWT("Aponta-Produto1");
		setMsgTextGWT(constants.digite_o_primeiro_item_que_voce_quer_comparar(), false);

		iswMulti.stopAnimacao();
		tmpVertPanelProd_Web.clear();
		txtBuscaProdMulti = new TextBox();
		txtBuscaProdMulti.setStylePrimaryName("textBoxPergunta");
		txtBuscaProdMulti.addStyleName("fontItemPergunta");
		txtBuscaProdMulti.addStyleName("boxShadow");
		txtBuscaProdMulti.addStyleName("backGroundTransition");
		txtBuscaProdMulti.setWidth("226px");

		HorizontalPanel horP = new HorizontalPanel();
		tmpVertPanelProd_Web.add(horP);
		tmpVertPanelProd_Web.setCellVerticalAlignment(horP, HasVerticalAlignment.ALIGN_MIDDLE);
		horP.add(txtBuscaProdMulti);

		final Button btnBuscaProd1 = new Button("&gt;&gt;");
		btnBuscaProd1.setStylePrimaryName("btnNext");
		horP.add(btnBuscaProd1);
		btnBuscaProd1.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				biProdMulti.addStyleName("boxShadow");
				biProdMulti.setBusca(txtBuscaProdMulti.getText());
			}
		});

		HorizontalPanel horP2 = new HorizontalPanel();
		tmpVertPanelProd_Web.add(horP2);
		tmpVertPanelProd_Web.setCellVerticalAlignment(horP2, HasVerticalAlignment.ALIGN_MIDDLE);
		biProdMulti = new BuscaImagemWidget();
		horP2.add(biProdMulti);

		//vertPanelProd1.add(btnConfirmaImagens);
		//vertPanelProd1.setCellVerticalAlignment(btnConfirmaImagens, HasVerticalAlignment.ALIGN_BOTTOM);
	
		biProdMulti.addImagemSelecionadaHandler(new BuscaImagemEventHandler() {
			@Override
			public void onListaPronta(ImagemDisponivelEvent event) {
				//btnConfirmaImagens.setEnabled(true);
			}
	
			@Override
			public void onListaNaoPronta(ImagemNaoDisponivelEvent event) {
				//btnConfirmaImagens.setEnabled(false);
			}

			@Override
			public void onImagensJaSelecionadas(ImagensJaSelecionadasEvent event) {
				ArrayList<String> listStrImagens = biProdMulti.getSelectedImagesSource();

				//tmpVertPanelProd1_Web.clear();
				txtBuscaProdMulti.removeStyleName("boxShadow");
				for (int i = 0; i < listStrImagens.size(); i++) {
					iswMulti.addImage(new Image(listStrImagens.get(i)));
				}

				ClientUtils.trocaWidgetWithFunction(tmpVertPanelProd_Web, new Callable() {
					@Override
					public void call() {
						showProd();
					}
				}, tmpVertPanelProd_Show, "", 0, 0, false, false, 0, 10, true, 1);
			}
		});
	}

	private void guiaCamProd(final VerticalPanel tmpVertPanelProd_Cam) {
		vertPanelAtualProdMulti = tmpVertPanelProd_Cam;
		guiaAtualProd = 2;

		carregaSequenciaExpressaoGWT("Aponta-Camera");
		setMsgTextGWT(constants.foto_da_sua_webcam_por_favor_permissao_permissao_para_usar_sua_camera(), false);

		iswMulti.stopAnimacao();
		tmpVertPanelProd_Cam.clear();
		htmlImg.setWidth("100%");
		htmlImg.getElement().getStyle().setDisplay(Display.NONE);
		//Canvas c = Canvas.createIfSupported();
		//c.getElement().setClassName("canvasVideo");
		//Context2d context = c.getContext2d();

		tmpVertPanelProd_Cam.add(htmlP);
		tmpVertPanelProd_Cam.add(htmlPCanvas);
		Button btnTiraFoto = new Button(constants.tirar_a_foto());
		tmpVertPanelProd_Cam.add(btnTiraFoto);		
		btnTiraFoto.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				tmpVertPanelProd_Cam.add(htmlImg);
				String dataUrl = foto();
				addStreamFotoComparacao(1, dataUrl);
				//Window.alert("Foto Tirada ok");
			}
		});

		loadCam(constants.clique_para_tirar_a_foto());
	}

	private void guiaFileProd(final VerticalPanel tmpVertPanelProd1_File) {
		vertPanelAtualProdMulti = tmpVertPanelProd1_File;
		guiaAtualProd = 3;

		carregaSequenciaExpressaoGWT("Aponta-Produto1");
		setMsgTextGWT(constants.vai_fazer_upload_selecione_ou_arreste_uma_foto_para_a_area_marcada(), false);

		iswMulti.stopAnimacao();
		tmpVertPanelProd1_File.clear();

		htmlImg.setWidth("100%");
		htmlImg.getElement().getStyle().setDisplay(Display.NONE);
		//Canvas c = Canvas.createIfSupported();
		//c.getElement().setClassName("canvasVideo");
		//Context2d context = c.getContext2d();

		tmpVertPanelProd1_File.add(htmlFile);
		tmpVertPanelProd1_File.add(htmlInputFile);

		startFileHandler(1);
	}

	private void addStreamFotoComparacao(int prodNum, String dataUrl) {
		//Window.alert("dataUrl = " + dataUrl);
		listImageDataUrlProd.add(dataUrl);
		//Window.alert("adicionou o dataurl ao lista");
		iswMulti.addImage(new Image(dataUrl));
		//Window.alert("adicionou a imagem do isw1");
		ClientUtils.trocaWidgetWithFunction(vertPanelAtualProdMulti, new Callable() {
			@Override
			public void call() {
				showProd();
			}
		}, tmpVertPanelProd_Show, "", 0, 0, false, false, 0, 10, true, 1);
	}

	private void maisProdutoOuContinua() {
		//Window.alert("solicitando produto1...1");
		setMsgTextGWT(constants.deseja_incluir_mais_um_item_na_comparacao(), false);
		//Window.alert("vai carregar a expressao");
		carregaSequenciaExpressaoGWT("Aponta-ProdMulti");
		//Window.alert("solicitando produto1...2");

		vertPanelProdMulti.clear();

		final Button btnNovoItem = new Button(constants.novo_item());
		vertPanelProdMulti.add(btnNovoItem);

		btnNovoItem.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				solicitaProduto();
			}
		});

		final Button btnContinua = new Button(constants.continuar());
		vertPanelProdMulti.add(btnContinua);

		btnContinua.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				carregaFormQualAPergunta();
			}
		});	
	}

	private void buscaImagem(final String busca) {
		resultsTable = new FlexTable();
	    SearchControlOptions options = new SearchControlOptions();
	    ImageSearch webSearch = new ImageSearch();
	    // Choose no HTML generation for quicker results.
	    webSearch.setNoHtmlGeneration();

	    for (int z = 0; z < ResultSetSize.values().length; z++) {
	    	System.out.println("Resultsize value: " + ResultSetSize.values()[z]);
	    }
	    webSearch.setResultSetSize(ResultSetSize.LARGE);
	    options.add(webSearch, ExpandMode.OPEN);
	    final SearchControl control = new SearchControl(options);

	    control.addSearchResultsHandler(new SearchResultsHandler() {
	    	public void onSearchResults(final SearchResultsEvent event) {

	    		final int pageNumber = event.getSearch().getCursor().getCurrentPageIndex();

	    		JsArray<? extends Result> results = event.getResults();
	    		System.out.println("número de resultados: " + results.length());
	    		System.out.println("número de paginas: " + event.getSearch().getCursor().getPages().length());
	    		System.out.println("Pagina atual: " + pageNumber);

	    		listCkImg = new CheckBox[results.length()];
	    		int i = 0;
	    		for (i = 0; i < results.length(); i++) {
	    			if (results.get(i).getResultClass().equals(ResultClass.IMAGE_SEARCH_RESULT)) {
	    				currentRow++;

	    				WebResult result = (WebResult) results.get(i);
	    				Image img = new Image(result.getUrl());
	    				img.setSize("100px", "100px");
	    				resultsTable.setWidget(0, i, img);
	    				listCkImg[i] = new CheckBox();
	    				listCkImg[i].setTitle(result.getUrl());
	    				listCkImg[i].addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								boolean encontrado = false;
								for (int k = 0; k < listCkImg.length; k++) {
									if (listCkImg[k].getValue()) {
										encontrado = true;
										break;
									}
								}

								horPanelImg.setVisible(!encontrado);

								if (encontrado) {
									if (horPProsseguir == null) {
										horPProsseguir = new HorizontalPanel();
									}
									if (horPProsseguir.getWidgetCount() == 0) {
										Button btnProsseguir = new Button(constants.proximo());
										horPProsseguir.add(btnProsseguir);
										rootProdMulti.add(horPProsseguir);
										btnProsseguir.addClickHandler(new ClickHandler() {
											@Override
											public void onClick(ClickEvent event) {
												carregaFormQualAPergunta();
											}
										});
									}
								} else {
									if (upload.getFilename().equals("")) {
										rootProdMulti.remove(horPProsseguir);
										horPProsseguir = null;
									}
								}
							}
						});
	    				resultsTable.setWidget(1, i, listCkImg[i]);
	    			}
	    		}
	    		Button btnMaisResultados = new Button("Mais&gt;&gt;");
	    		btnMaisResultados.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent ev) {
						event.getSearch().gotoPage(pageNumber + 1);
					}
				});
	    		resultsTable.setWidget(0, i, btnMaisResultados);
	    		if (horPanelImg.getWidgetCount() == 0) {
	    			horPanelImg.add(new Label("Use sua própria foto:"));
	    			upload = new FileUpload();
	    			upload.addChangeHandler(new ChangeHandler() {
	    				@Override
	    				public void onChange(ChangeEvent event) {
	    					Window.alert("selecionou arquivo!!");
	    				}
	    			});
	    			horPanelImg.add(upload);
	    		}
	    	}
	    });

	    vertPImages.clear();
	    vertPImages.add(new Label("Selecione as imagens que descrevem o item:"));
	    ScrollPanel scroll = new ScrollPanel(resultsTable);
	    scroll.setWidth("400px");
	    scroll.setHeight("150px");
	    vertPImages.add(scroll);

	    control.execute(busca);
	}

	private void removeEventoLabelProd1() {
		if (lbHldRegisProd1 != null) {
			lbHldRegisProd1.removeHandler();
			lbHldRegisProd1 = null;
		}
		if (lbHldRegisProd1_blur != null) {
			lbHldRegisProd1_blur.removeHandler();
			lbHldRegisProd1_blur = null;
		}
		//Window.alert("txtBuscaProd1 = [" + txtBuscaProd1.getText() + "], lbProd1 = [" + lbProduto1.getText() + "]");
		if (!txtBuscaProdMulti.getText().equals(lbProduto.getText())) {
			lbProduto.setText(txtBuscaProdMulti.getText().trim());
			ClientUtils.trocaWidgetWithFunction(txtBuscaProdMulti,
					new Callable() {
						@Override
						public void call() {
						}
					},
					lbProduto, "", 0, 0, false, false, 0, 10, true, 1);
		}
	}

	private void aplicaEventoLabelProd(final String parentType, final int param1, final int param2) {
		if (lbHldRegisProd1 != null) {
			lbHldRegisProd1.removeHandler();
			lbHldRegisProd1 = null;
		}
		lbHldRegisProd1 = lbProduto.addMouseOverHandler(new MouseOverHandler() {
			@Override
			public void onMouseOver(MouseOverEvent event) {
				if (lbHldRegisProd1 != null) {
					lbHldRegisProd1.removeHandler();
					lbHldRegisProd1 = null;
				}
				txtBuscaProdMulti.setStylePrimaryName("textBoxPerguntaEdicao");
				ClientUtils.trocaWidgetWithFunction(lbProduto,
													new Callable() {
														@Override
														public void call() {
															txtBuscaProdMulti.selectAll();
															lbHldRegisProd1 = txtBuscaProdMulti.addMouseOutHandler(new MouseOutHandler() {
																@Override
																public void onMouseOut(MouseOutEvent event) {
																	//Window.alert("mouseout");
																	if (lbHldRegisProd1 != null) {
																		lbHldRegisProd1.removeHandler();
																		lbHldRegisProd1 = null;
																	}
																	if (lbHldRegisProd1_blur != null) {
																		lbHldRegisProd1_blur.removeHandler();
																		lbHldRegisProd1_blur = null;
																	}
																	lbProduto.setText(txtBuscaProdMulti.getText());
																	ClientUtils.trocaWidgetWithFunction(txtBuscaProdMulti,
																										new Callable() {
																											@Override
																											public void call() {
																												aplicaEventoLabelProd(parentType, param1, param2);
																											}
																										},
																										lbProduto, parentType, param1, param2, false, false, 0, 10, true, 2);
																}
															});

															lbHldRegisProd1_blur = txtBuscaProdMulti.addBlurHandler(new BlurHandler() {
																@Override
																public void onBlur(BlurEvent event) {
																	//Window.alert("blurout");
																	if (lbHldRegisProd1_blur != null) {
																		lbHldRegisProd1_blur.removeHandler();
																		lbHldRegisProd1_blur = null;
																	}
																	if (lbHldRegisProd1 != null) {
																		lbHldRegisProd1.removeHandler();
																		lbHldRegisProd1 = null;
																	}
																	lbProduto.setText(txtBuscaProdMulti.getText());

																	ClientUtils.trocaWidgetWithFunction(txtBuscaProdMulti,
																										new Callable() {
																											@Override
																											public void call() {
																												aplicaEventoLabelProd(parentType, param1, param2);
																											}
																										},
																										lbProduto, parentType, param1, param2, false, false, 0, 10, true, 2);
																}
															});

														}
													},
													txtBuscaProdMulti, parentType, param1, param2, true, false, 100, 10, true, 2);
			}
		});
	}

	private void gravaComparacao1Coisa(Long idUsuario, String nomeProduto, ArrayList<String> listEnderecoFoto) {
		if (serviceSupportSvc == null) {
			serviceSupportSvc = GWT.create(ISessionSuportService.class);
		}

		GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
			@Override
			public void onUncaughtException(Throwable e) {
				e.printStackTrace();
				System.out.println("Excecao nao tratada em Horario Carrega Sessao !!!!!!!!!!");
			}
		});

		AsyncCallback<Comparacao> callback = new AsyncCallback<Comparacao>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Erro ao tentar gravar! Por favor, aperte a tecla F5 do seu teclado para atualizar!");
			}

			@Override
			public void onSuccess(Comparacao comp) {
				if (comp == null) {
					Window.alert("Erro ao tentar gravar! Por favor, aperte a tecla F5 do seu teclado para atualizar!");	
				} else {
					Window.Location.replace("/comparacao/" + comp.getPath(ParametrosSistema.SiteHost.SITE_QUAL_O_MELHOR));
				}
			}
		};
		System.out.println("Salvando comparacao: idUsuario: " + idUsuario + ", nomeProduto = " + nomeProduto + ", enderecoFoto.size = " + listEnderecoFoto.size());
		//serviceSupportSvc.gravaComparacao1Coisa(idUsuario, nomeProduto, listEnderecoFoto, new ArrayList<Blob>(0), ParametrosSistema.SiteHost.valueOf(listPerguntas.getValue(listPerguntas.getSelectedIndex())), txtPerguntaIntermed.getText(), callback);
	}
}